package com.gzw.shop.adapter;

import android.content.Context;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.gzw.shop.R;
import com.gzw.shop.bean.Address;

import java.util.List;

/**
 * Created by JACKYGUO on 2017-05-09.
 */

public class AddressAdapter extends SimpleAdapter<Address> {

    private AddressListener listener;

    public AddressAdapter(Context context, List<Address> datas, AddressListener listener) {
        super(context, datas, R.layout.template_address);
        this.listener = listener;
    }

    @Override
    public void bindData(BaseViewHolder holder, final Address address) {

        holder.getTextView(R.id.txt_name).setText(address.getConsignee());
        holder.getTextView(R.id.txt_phone).setText(replacePhone(address.getPhone()));
        holder.getTextView(R.id.txt_address).setText(address.getAddr());

        holder.getTextView(R.id.txt_del).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.deleteAddress(address.getId());
                }
            }
        });

        holder.getTextView(R.id.txt_edit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.editAddress(address);
                }
            }
        });

        final CheckBox checkBox = holder.getCheckBox(R.id.cb_is_defualt);
        final boolean isDefault = address.getIsDefault();
        checkBox.setChecked(isDefault);
        if (isDefault) {
            checkBox.setText("默认地址");
        } else {
            checkBox.setClickable(true);
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked && listener != null) {
                        address.setIsDefault(true);
                        listener.setDefault(address, isChecked);
                    }
                }
            });
        }
    }

    private String replacePhone(String phone) {
        return phone.substring(0, phone.length() - (phone.substring(3)).length()) + "****" + phone.substring(7);
    }

    public interface AddressListener {
        public void setDefault(Address address, boolean isDefault);

        public void deleteAddress(long id);

        public void editAddress(Address address);
    }
}
